package pri.hillchen.std.concurrent.chapter14.boundedbuffer;

import java.util.concurrent.TimeUnit;

/**
 * @author:hillchen
 * @DESCRIPTION:
 * @Date: Created in 10:28 2018/2/1 0013.
 */
public class BoundedBuffer<V> extends BaseBoundedBuffer<V> {
    public BoundedBuffer(int capacity) {
        super(capacity);
    }
    public synchronized void put(V ele) throws  InterruptedException {
        while (isFull()){
            this.wait();
        }
        doPut(ele);
        notifyAll();
    }

    public synchronized V take() throws InterruptedException {
        while (isEmpty()){
            this.wait();
        }
        V ret = doTake();
        this.notifyAll();
        return ret;
    }

    public static void main(String[] args) throws InterruptedException {

        final BoundedBuffer<Integer> boundedBuffer = new BoundedBuffer<>(10);
        for(int i = 0; i<10;i++){
            boundedBuffer.put(i);
        }
        for(int i = 0; i<10;i++){
            System.out.println(boundedBuffer.take());
        }

        new Thread(){
            @Override
            public void run() {
                try {
                    System.out.println(boundedBuffer.take());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();
        new Thread(){
            @Override
            public void run() {
                try {
                    TimeUnit.SECONDS.sleep(1);
                    boundedBuffer.put(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }.start();

    }
}
